
package db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import bean.AraStoreLog;
import bean.ItemPriceAccountModel;

import bean.TradeAccountConsumptionFlow;
import bean.TradeConsumptionDetail;
import bean.TradeConsumptionMain;
import config.CommonValue;
import tools.StringUtils;
import tools.TimeTools;


/**
 * Created by TJ on 2016/3/2.
 */
public class TaskManager {
    private static final String TAG = "TaskManager";
    private static TaskManager taskManager;
    private static DBManager dbManager;
    private SQLiteDatabase dataBase;//数据库连接
    private Context context;
    public final static String TIMEOUT_ERROR = "服务器无法连接或处理超时";//无法连接或处理超时
    public final static String SERVER_BIZ_ERROR = "服务器应用程序运行异常";//后台应用程序报错
    public final static String APP_BIZ_ERROR = "APP业务处理异常";//APP内业务处理异常

    private TaskManager(Context context) {
        this.context = context;
        String databaseName = CommonValue.DATABASE_NAME;
        if (CommonValue.isDebug)
        dbManager = DBManager.getInstance(context, databaseName);
    }

    public static TaskManager getInstance(Context context) {
        if (taskManager == null) {
            taskManager = new TaskManager(context.getApplicationContext());
        }
        return taskManager;
    }

    public static void destroy() {
        taskManager = null;
        dbManager = null;
    }

    public void openDB() {
        dataBase = dbManager.openDatabase();
    }

    public void closeDB(){
        dbManager.closeDatabase(dataBase, null);
    }

    public void showToast(String text) {
        Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
    }


    /**
     * 更新表中信息
     *
     * @param table
     * @param values
     * @param whereClause
     * @param whereArgs
     * @return
     */
    public int update(String table, ContentValues values, String whereClause,
                      String[] whereArgs) {
        try {
            if (dataBase == null ){
                dataBase = dbManager.openDatabase();
            }
            return dataBase.update(table, values, whereClause, whereArgs);
        } catch (Exception e) {
            if (CommonValue.isDebug)
            showToast(APP_BIZ_ERROR);
        } finally {
            dbManager.closeDatabase(dataBase, null);
        }
        return 0;
    }

    /**
     * 根据主键_id删除记录
     *
     * @param table
     * @param ids
     * @return
     */
    public int deleteByIds(String table, String... ids) {
        try {
            if (ids == null || ids.length == 0)
                return 0;
            StringBuilder sb = new StringBuilder("_id in(");
            for (int i = 0, m = ids.length; i < m; i++) {
                if (i > 0) {
                    sb.append(",");
                }
                sb.append("?");
            }
            if (dataBase == null) {
                dataBase = dbManager.openDatabase();
            }
            return dataBase.delete(table, sb.append(")").toString(), ids);
        } catch (Exception e) {
            if (CommonValue.isDebug)
            showToast(APP_BIZ_ERROR);
        } finally {
            dbManager.closeDatabase(dataBase, null);
        }
        return 0;
    }

    /**
     * 根据表名删除表
     *
     * @param tableName
     * @return
     */
    public int deleteTable(String tableName) {
        try {
            if (tableName == null || tableName.equals(""))
                return 0;
//            dataBase = dbManager.openDatabase();
            dataBase.execSQL("delete from " + tableName);
            Log.e("删除成功", tableName);
            return 1;
        } catch (Exception e) {
            if (CommonValue.isDebug)

            showToast(APP_BIZ_ERROR);
            return 0;
        } finally {
//            dbManager.closeDatabase(dataBase, null);
        }

    }


    /**
     * 列表查询
     *
     * @param table
     * @param columns
     * @param selection
     * @param selectionArgs
     * @param orderBy
     * @param rowMapper
     * @param <T>
     * @return
     */
    public <T> List<T> listQuery(String table, String[] columns, String selection, String[] selectionArgs,
                                 String orderBy, RowMapper<T> rowMapper) {
        Cursor cursor = null;
        List<T> list = null;
        try {
            if (dataBase == null) {
                dataBase = dbManager.openDatabase();
            }
            cursor = dataBase.query(table, columns, selection, selectionArgs, null, null, orderBy, null);
            list = new ArrayList<T>();
            while (cursor.moveToNext()) {
                list.add(rowMapper.mapRow(cursor, cursor.getPosition()));
            }
        } catch (Exception e) {
            return null;
        } finally {
            dbManager.closeDatabase(dataBase, cursor);
        }
        return list;
    }




    public List<TradeAccountConsumptionFlow> queryUploadConsumptionFlow(String startTime, String endTime, String flowNo) {
            Cursor cursor = null;
            RowMapper<TradeAccountConsumptionFlow> rowMapper = new RowMapper<TradeAccountConsumptionFlow>() {
                @Override
                public TradeAccountConsumptionFlow mapRow(Cursor cursor, int index) {
                    return TaskManager.this.mapUploadConsumptionFlow(cursor, index);
                }
            };
            List<TradeAccountConsumptionFlow> list = new ArrayList<TradeAccountConsumptionFlow>();
            try {
                if (dataBase == null) {
                    dataBase = dbManager.openDatabase();
                }
//                Calendar calendar = Calendar.getInstance();
//                calendar.add(Calendar.DATE,-7);
//                String startOfDay = TimeTools.startOfDay(calendar);
                /* String endOfDay = TimeTools.endOfDay(calendar);*/
                StringBuilder str = new StringBuilder("select * from trade_account_consumption_flow t  ");
                str.append(" where isXmlOut = '0' ");
                str.append(" and orderStatus = '1' ");
//             str.append(" and createTime<= ").append("'"+endOfDay+"'");
                str.append(" and createTime>= ").append("'"+startTime+"'");
                str.append(" and createTime < ").append("'"+endTime+"'");
                if (!StringUtils.empty(flowNo)){
                    str.append(" and flowNo = '"+flowNo+"'");
                }

                cursor = dataBase.rawQuery(str.toString(), null);

                while (cursor.moveToNext()) {
                    TradeAccountConsumptionFlow tradeFlow = rowMapper.mapRow(cursor, cursor.getPosition());
                    list.add(tradeFlow);
                }
            } finally {
                dbManager.closeDatabase(dataBase, cursor);
            }
            return list;
    }
    //刷卡获取flow
    public List<TradeAccountConsumptionFlow> getConsumptionFlow(String startTime, String endTime, String cardId,String customerNo) {
        Cursor cursor = null;
        RowMapper<TradeAccountConsumptionFlow> rowMapper = new RowMapper<TradeAccountConsumptionFlow>() {
            @Override
            public TradeAccountConsumptionFlow mapRow(Cursor cursor, int index) {
                return TaskManager.this.mapUploadConsumptionFlow(cursor, index);
            }
        };
        List<TradeAccountConsumptionFlow> list = new ArrayList<TradeAccountConsumptionFlow>();
        try {
            if (dataBase == null) {
                dataBase = dbManager.openDatabase();
            }
//                Calendar calendar = Calendar.getInstance();
//                calendar.add(Calendar.DATE,-7);
//                String startOfDay = TimeTools.startOfDay(calendar);
            /* String endOfDay = TimeTools.endOfDay(calendar);*/
            StringBuilder str = new StringBuilder("select * from trade_account_consumption_flow t  ");
//             str.append(" and createTime<= ").append("'"+endOfDay+"'");
            str.append(" where createTime>= ").append("'"+startTime+"'");
            str.append(" and createTime < ").append("'"+endTime+"'");
            if (!StringUtils.empty(cardId)){
                str.append(" and card = '"+cardId+"'");
            }
            if (!StringUtils.empty(customerNo)){
                str.append(" and customer = '"+customerNo+"'");
            }
            str.append(" and orderStatus = '1' ");
            str.append(" ORDER BY createTime desc ");
            cursor = dataBase.rawQuery(str.toString(), null);

            while (cursor.moveToNext()) {
                TradeAccountConsumptionFlow tradeFlow = rowMapper.mapRow(cursor, cursor.getPosition());
                list.add(tradeFlow);
            }
        } finally {
            dbManager.closeDatabase(dataBase, cursor);
        }
        return list;
    }

    public List<AraStoreLog> queryUploadAraStoreLog(String startTime, String endTime) {
        Cursor cursor = null;
        RowMapper<AraStoreLog> rowMapper = new RowMapper<AraStoreLog>() {
            @Override
            public AraStoreLog mapRow(Cursor cursor, int index) {
                return TaskManager.this.mapUploadAraStoreLog(cursor, index);
            }
        };
        try {
            if (dataBase == null) {
                dataBase = dbManager.openDatabase();
            }
//            Calendar calendar = Calendar.getInstance();
//            calendar.add(Calendar.DATE,-7);
//            String startOfDay = TimeTools.startOfDay(calendar);
            /* String endOfDay = TimeTools.endOfDay(calendar);*/
            StringBuilder str = new StringBuilder("select * from ara_store_log t  ");
            str.append(" where isSyn = '0' ");
            // str.append(" and createTime<= ").append("'"+endOfDay+"'");
            str.append(" and createTime >= ").append("'"+startTime+"'");
            str.append(" and createTime < ").append("'"+endTime+"'");
//            str.append(" and orderNo = '201905141037128cca'");

            cursor = dataBase.rawQuery(str.toString(), null);
            List<AraStoreLog> list = new ArrayList<AraStoreLog>();
            while (cursor.moveToNext()) {
                AraStoreLog araStoreLog = rowMapper.mapRow(cursor, cursor.getPosition());
                list.add(araStoreLog);
            }
            return list;
        } finally {
            dbManager.closeDatabase(dataBase, cursor);
        }

    }

    public String findTradeMainIdByFlowNo(String flowNo) {
        RowMapper<String> rowMapper = new RowMapper<String>() {
            @Override
            public String mapRow(Cursor cursor, int index) {
                return cursor.getString(cursor.getColumnIndex("id"));
            }
        };
        List<String> list = taskManager.listQuery("trade_consumption_main", new String[]{"id"}, "flowNo=?", new String[]{flowNo}, null, rowMapper);
        return list != null && list.size() > 0 ? list.get(0) : null;
    }

    public void updateStatusAraLog(List<AraStoreLog> uploadAraStoreLog, List<String> okOrderNoLists) {
        boolean flag = okOrderNoLists == null || okOrderNoLists.size() <1;
        if (flag) return;
        //更新状态
        ContentValues values = new ContentValues();
        values.put("isSyn","1");//key为字段名，value为值
        try {
            if (dataBase == null) {
                dataBase = dbManager.openDatabase();
            }
            dataBase.beginTransaction();
            for (String orderNo : okOrderNoLists) {
                try {
                    dataBase.update("ara_store_log", values, "orderNo=?", new String[]{orderNo });
                    Log.e(TAG, "ara_store_log: 更新状态成功【" +  orderNo+"】");

                } catch (Exception e) {
                    Log.e(TAG, "ara_store_log: 更新状态失败【" +  orderNo+"】");
                }
            }
            dataBase.setTransactionSuccessful();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            dataBase.endTransaction();
            dbManager.closeDatabase(dataBase, null);
        }
    }

    public void saveAraStoreLog(AraStoreLog araLog) {

        try {
            if (dataBase == null) {
                dataBase = dbManager.openDatabase();
            }
            long count1 = dataBase.insert("ara_store_log", null, parseAraStoreLog(araLog));//存微信日志表
            if (count1 > 0) {
                Log.d(TAG, "saveAraStoreLog: 日志保存成功");
            }
        } finally {
            dbManager.closeDatabase(dataBase, null);
        }
    }

    public List<TradeConsumptionMain> listTradeTask(String flowNo) {
        String selection  = " flowNo=? ";
        String[] selectionArgs = new String[]{flowNo};
        List<TradeConsumptionMain> mainLists = listQuery("trade_consumption_main", null, selection, selectionArgs,null, mainRowMapper);
        String subSelection  = " mainId = ? ";
        String[] subSelectionArgs = new String[1];
        List<TradeConsumptionDetail> details = null;
        List<TradeConsumptionMain> list = new ArrayList<>();
        Cursor cursor = null;
        try {
            if (dataBase == null) {
                dataBase = dbManager.openDatabase();
            }
            cursor = dataBase.query("trade_consumption_main", null, selection, selectionArgs, null, null, null, null);
            while (cursor.moveToNext()) {
                list.add(mainRowMapper.mapRow(cursor, cursor.getPosition()));
            }
            if (list == null || list.size() < 1) return null;

            for (TradeConsumptionMain main : list) {
                subSelectionArgs[0] = main.getId();
                details = listQuery("trade_consumption_detail", null, subSelection, subSelectionArgs, null, detailRowMapper);
                main.setDetailLists(details);
            }
        } catch (Exception e) {
            return null;
        } finally {
            dbManager.closeDatabase(dataBase, cursor);
        }

        return list;
    }
    public List<TradeConsumptionMain> listTradeTaskByOrderStatus() {
        String selection  = "  orderStatus=? and createTime>=?";
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE,-5);
        String timeStr = TimeTools.calendar2String(calendar);
        String[] selectionArgs = new String[]{"0",timeStr};
        List<TradeConsumptionMain> mainLists = listQuery("trade_consumption_main", null, selection, selectionArgs,null, mainRowMapper);
        String subSelection  = " mainId = ? ";
        String[] subSelectionArgs = new String[1];
        List<TradeConsumptionDetail> details = null;
        List<TradeConsumptionMain> list = new ArrayList<>();
        Cursor cursor = null;
        try {
            if (dataBase == null) {
                dataBase = dbManager.openDatabase();
            }
            cursor = dataBase.query("trade_consumption_main", null, selection, selectionArgs, null, null, null, null);
            while (cursor.moveToNext()) {
                list.add(mainRowMapper.mapRow(cursor, cursor.getPosition()));
            }
            if (list == null || list.size() < 1) return null;

            for (TradeConsumptionMain main : list) {
                subSelectionArgs[0] = main.getId();
                details = listQuery("trade_consumption_detail", null, subSelection, subSelectionArgs, null, detailRowMapper);
                main.setDetailLists(details);
            }
        } catch (Exception e) {
            return null;
        } finally {
            dbManager.closeDatabase(dataBase, cursor);
        }

        return list;
    }

    RowMapper<TradeConsumptionDetail> detailRowMapper = new RowMapper<TradeConsumptionDetail>() {
        @Override
        public TradeConsumptionDetail mapRow(Cursor cursor, int index) {
            return TaskManager.this.mapUploadConsumptionDetail(cursor, index);
        }
    };

    RowMapper<TradeConsumptionMain> mainRowMapper =  new RowMapper<TradeConsumptionMain>() {
        @Override
        public TradeConsumptionMain mapRow(Cursor cursor, int index) {
            return TaskManager.this.mapUploadConsumptionMain(cursor, index);
        }
    };



    public interface RowMapper<T> {
        /**
         * @param cursor 游标
         * @param index  下标索引
         * @return
         */
        public T mapRow(Cursor cursor, int index);
    }



    //支付宝用：将微信交易日志以及流水等三张表存到本地
    public int payInsertAraStoreLog(AraStoreLog log , List<ItemPriceAccountModel> listModel,boolean micPay) {
        int result = 0;
        if (log == null)
            return result;
            try {
                if (dataBase == null) {
                    dataBase = dbManager.openDatabase();
                }
                long count1 = dataBase.insert("ara_store_log", null, parseAraStoreLog(log));//存微信日志表
                Log.e("count1",count1+"");
                if (count1 != -1)
                    result+=1;
                if (CommonValue.isDebug)
                    Log.i("TaskManager", "insert to local AraStoreLog：" + result);

                //存储流水表等
                if (micPay) {
                    //if (true) {
                    if (log.getDiscountAmount()==null||log.getDiscountAmount().equals("")){
                        log.setDiscountAmount("0");
                    }
                    String transaction_id = log.getOrderNo();
                    TradeAccountConsumptionFlow tradeFlow = new TradeAccountConsumptionFlow();//流水表
                    tradeFlow.setId(UUID.randomUUID().toString().substring(0, 32));
                    tradeFlow.setMealTime(listModel.get(0).getMealTime());
                    tradeFlow.setFlowNo(transaction_id);
                    //tradeFlow.setFlowNo("123456789");
                    tradeFlow.setActualAmount(Double.parseDouble(log.getAmount()));
                    tradeFlow.setDiscountAmount(Double.parseDouble(log.getDiscountAmount()));
                    //tradeFlow.setActualAmount(Double.parseDouble(100+""));//微信传整数测试
                    tradeFlow.setCreateTime(TimeTools.calendar2String(Calendar.getInstance()));
                    tradeFlow.setIsXmlOut("0");
                    tradeFlow.setReason(log.getZfType());
                    if (!"".equals(log.getAccountId())){
                        tradeFlow.setAccountId(log.getAccountId());
                    }
                    if (!"".equals(log.getCustomerId())){
                        tradeFlow.setCustomer(log.getCustomerId());
                    }
                    if (!"".equals(log.getCardId())){
                        tradeFlow.setCard(log.getCardId());
                    }
                    tradeFlow.setOrderStatus("0");
                    long count2 = dataBase.insert("trade_account_consumption_flow", null, parseTradeAccountConsumptionFlow(tradeFlow));
                    Log.e("count2", count2 + "");
                    if (count2 != -1)
                        result += 2;
                    TradeConsumptionMain tradeMain = new TradeConsumptionMain();//主表
                    tradeMain.setId(UUID.randomUUID().toString().substring(0, 32));
                    tradeMain.setFlowNo(transaction_id);
                    tradeMain.setMealTime(listModel.get(0).getMealTime());
                    tradeMain.setQuantity(Double.parseDouble(listModel.size() + ""));
                    tradeMain.setActualAmount(Double.parseDouble(log.getAmount()));
                    tradeMain.setDiscountAmount(Double.parseDouble(log.getDiscountAmount()));
                    //tradeMain.setActualAmount(Double.parseDouble(result+"") / 100);//微信传整数测试
                    tradeMain.setCreateTime(TimeTools.calendar2String(Calendar.getInstance()));
                    tradeMain.setReason(log.getZfType());
                    tradeMain.setConsumptionTime(TimeTools.calendar2String(Calendar.getInstance()));
                    tradeMain.setIsXmlOut("0");

                    tradeMain.setCustomerAddress(log.getCustomerAddress());
                    if (!"".equals(log.getCustomerAddress()) && log.getCustomerAddress() != null) {
                        String[] split = log.getCustomerAddress().split("\\|");
                        tradeMain.setCustomerFloor(split[0]);
                    }
                    tradeMain.setPrintStatus(log.getPrintStatus());
                    tradeMain.setCustomerPhone(log.getCustomerPhone());
                    tradeMain.setCustomerName(log.getCustomerName());
                    tradeMain.setTableNo(log.getTableNo());
                    tradeMain.setCustomerArchitecture(log.getCustomerArchitecture());
                    tradeMain.setOrderStatus("0");
                    dataBase.insert("trade_consumption_main", null, parseTradeConsumptionMain(tradeMain));
                    double dis = Double.parseDouble(log.getDiscountAmount());
                    for (ItemPriceAccountModel item : listModel) {
                        TradeConsumptionDetail tradeDetail = new TradeConsumptionDetail();//明细表
                        tradeDetail.setId(UUID.randomUUID().toString().substring(0, 32));
                        tradeDetail.setMainId(tradeMain.getId());
                        tradeDetail.setFoodId(item.getItemId());
                        tradeDetail.setBusinessTypeId(item.getBusinessTypeId());
                        tradeDetail.setPrice(Double.parseDouble(item.getPrice() + ""));
                        tradeDetail.setQuantity(Double.parseDouble(item.getNumber() + ""));

                        if (dis>0&&tradeDetail.getPrice() * tradeDetail.getQuantity()<=dis){
                            tradeDetail.setActualAmount(0.0);
                            tradeDetail.setHandDiscount(tradeDetail.getPrice() * tradeDetail.getQuantity());
                            dis = dis-tradeDetail.getPrice() * tradeDetail.getQuantity();
                        }else{
                            tradeDetail.setActualAmount(tradeDetail.getPrice() * tradeDetail.getQuantity()-dis);
                            tradeDetail.setHandDiscount(dis);
                            dis=0.0;
                        }
                        tradeDetail.setIsXmlOut("0");
                        tradeDetail.setReason(log.getZfType());
                        tradeDetail.setRefundStatus("0");
                        long count4 = dataBase.insert("trade_consumption_detail", null, parseTradeConsumptionDetail(tradeDetail));
                        Log.e("count4", count4 + "");
                        if (count4 < 0){
                            return result;
                        }
                    }
                    result += 4;
                }

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                dbManager.closeDatabase(dataBase, null);
            }
            return result;

    }
    //微信用：将微信交易日志以及流水等三张表存到本地
    public int insertAraStoreLog(AraStoreLog log , List<ItemPriceAccountModel> listModel,Map<String,String> micPay) {
        int result = 0;
        if (log == null)
            return result;
            try {
                if (dataBase == null) {
                    dataBase = dbManager.openDatabase();
                }
                dataBase.beginTransaction();
                long count1 = dataBase.insert("ara_store_log", null, parseAraStoreLog(log));//存微信日志表
                Log.e("count1",count1+"");
                if (count1 != -1)
                    result+=1;
                if (CommonValue.isDebug)
                    Log.i("TaskManager", "insert to local AraStoreLog：" + result);

                //存储流水表等
                if (micPay != null) {
                    //if (true) {
                    String transaction_id = log.getOrderNo();
                    TradeAccountConsumptionFlow tradeFlow = new TradeAccountConsumptionFlow();//流水表
                    tradeFlow.setId(UUID.randomUUID().toString().substring(0, 32));
                    tradeFlow.setMealTime(listModel.get(0).getMealTime());
                    tradeFlow.setFlowNo(transaction_id);
                    //tradeFlow.setFlowNo("123456789");
                    tradeFlow.setActualAmount(Double.parseDouble(log.getAmount()) / 100);//微信传整数
                    //tradeFlow.setActualAmount(Double.parseDouble(100+""));//微信传整数测试
                    tradeFlow.setCreateTime(TimeTools.calendar2String(Calendar.getInstance()));
                    tradeFlow.setIsXmlOut("0");
                    tradeFlow.setReason("W");
                    long count2 = dataBase.insert("trade_account_consumption_flow", null, parseTradeAccountConsumptionFlow(tradeFlow));
                    Log.e("count2", count2 + "");
                    if (count2 != -1)
                        result += 2;
                    TradeConsumptionMain tradeMain = new TradeConsumptionMain();//主表
                    tradeMain.setId(UUID.randomUUID().toString().substring(0, 32));
                    tradeMain.setFlowNo(transaction_id);
                    tradeMain.setMealTime(listModel.get(0).getMealTime());
                    tradeMain.setQuantity(Double.parseDouble(listModel.size() + ""));
                    tradeMain.setActualAmount(Double.parseDouble(log.getAmount()));//微信传整数
                    //tradeMain.setActualAmount(Double.parseDouble(result+"") / 100);//微信传整数测试
                    tradeMain.setCreateTime(TimeTools.calendar2String(Calendar.getInstance()));
                    tradeMain.setReason("W");
                    tradeMain.setConsumptionTime(TimeTools.calendar2String(Calendar.getInstance()));
                    tradeMain.setIsXmlOut("0");
                    tradeMain.setCustomerAddress(log.getCustomerAddress());
                    tradeMain.setCustomerPhone(log.getCustomerPhone());
                    tradeMain.setCustomerName(log.getCustomerName());
                    tradeMain.setTableNo(log.getTableNo());
                    tradeMain.setCustomerArchitecture(log.getCustomerArchitecture());
                    tradeMain.setOrderStatus("1");
                    if (!"".equals(log.getCustomerAddress()) && log.getCustomerAddress() != null) {
                        String[] split = log.getCustomerAddress().split("\\|");
                        tradeMain.setCustomerFloor(split[0]);
                    }
                    tradeMain.setPrintStatus(log.getPrintStatus());
                    dataBase.insert("trade_consumption_main", null, parseTradeConsumptionMain(tradeMain));

                    for (ItemPriceAccountModel item : listModel) {
                        TradeConsumptionDetail tradeDetail = new TradeConsumptionDetail();//明细表
                        tradeDetail.setId(UUID.randomUUID().toString().substring(0, 32));
                        tradeDetail.setMainId(tradeMain.getId());
                        tradeDetail.setFoodId(item.getItemId());
                        tradeDetail.setBusinessTypeId(item.getBusinessTypeId());
                        tradeDetail.setPrice(Double.parseDouble(item.getPrice() + ""));
                        tradeDetail.setQuantity(Double.parseDouble(item.getNumber() + ""));
                        tradeDetail.setActualAmount(tradeDetail.getPrice() * tradeDetail.getQuantity());
                        tradeDetail.setIsXmlOut("0");
                        tradeDetail.setReason("W");
                        tradeDetail.setRefundStatus("0");
                        long count4 = dataBase.insert("trade_consumption_detail", null, parseTradeConsumptionDetail(tradeDetail));

                        Log.e("count4", count4 + "");
                        if (count4 != -1)
                            result += 4;
                    }

                }
                dataBase.setTransactionSuccessful();
                dataBase.endTransaction();
            } catch (Exception e) {
            } finally {
                dbManager.closeDatabase(dataBase, null);
            }
            return result;



    }//刷卡用：将微信交易日志以及流水等三张表存到本地
    public int cradinsertAraStoreLog(AraStoreLog log , List<ItemPriceAccountModel> listModel,Map<String,String> micPay) {
        int result = 0;
        if (log == null)
            return result;
            try {
                if (dataBase == null) {
                    dataBase = dbManager.openDatabase();
                }
                dataBase.beginTransaction();
                long count1 = dataBase.insert("ara_store_log", null, parseAraStoreLog(log));//存微信日志表
                Log.e("count1",count1+"");
                if (count1 != -1)
                    result+=1;
                if (CommonValue.isDebug)
                    Log.i("TaskManager", "insert to local AraStoreLog：" + result);

                //存储流水表等
                if (micPay != null) {
                //if (true) {
                    String transaction_id = log.getOrderNo();
                    TradeAccountConsumptionFlow tradeFlow = new TradeAccountConsumptionFlow();//流水表
                    tradeFlow.setId(UUID.randomUUID().toString().substring(0,32));
                    tradeFlow.setMealTime(listModel.get(0).getMealTime());
                    tradeFlow.setFlowNo(transaction_id);
                    tradeFlow.setActualAmount(Double.parseDouble(log.getAmount()));
                    tradeFlow.setCreateTime(TimeTools.calendar2String(Calendar.getInstance()));
                    tradeFlow.setIsXmlOut("0");
                    tradeFlow.setReason("C");
                    tradeFlow.setAccountId(log.getAccountId());
                    tradeFlow.setCustomer(log.getCustomerId());
                    tradeFlow.setCard(log.getCardId());
                    long count2 = dataBase.insert("trade_account_consumption_flow", null, parseTradeAccountConsumptionFlow(tradeFlow));
                    Log.e("count2",count2+"");
                    if (count2 != -1)
                        result+=2;
                    TradeConsumptionMain tradeMain = new TradeConsumptionMain();//主表
                    tradeMain.setId(UUID.randomUUID().toString().substring(0,32));
                    tradeMain.setFlowNo(transaction_id);
                    tradeMain.setMealTime(listModel.get(0).getMealTime());
                    tradeMain.setQuantity(Double.parseDouble(listModel.size() + ""));
                    tradeMain.setActualAmount(Double.parseDouble(log.getAmount()));
                    tradeMain.setCreateTime(TimeTools.calendar2String(Calendar.getInstance()));
                    tradeMain.setReason("C");
                    tradeMain.setConsumptionTime(TimeTools.calendar2String(Calendar.getInstance()));
                    tradeMain.setIsXmlOut("0");
                    tradeMain.setCustomerAddress(log.getCustomerAddress());
                    tradeMain.setCustomerPhone(log.getCustomerPhone());
                    tradeMain.setCustomerName(log.getCustomerName());
                    tradeMain.setTableNo(log.getTableNo());
                    tradeMain.setCustomerArchitecture(log.getCustomerArchitecture());
                    if (!"".equals(log.getCustomerAddress()) && log.getCustomerAddress()!=null){
                        String[] split = log.getCustomerAddress().split("\\|");
                        tradeMain.setCustomerFloor(split[0]);
                    }
                    tradeMain.setPrintStatus(log.getPrintStatus());
                    tradeMain.setOrderStatus("1");
                    dataBase.insert("trade_consumption_main", null, parseTradeConsumptionMain(tradeMain));

                    for (ItemPriceAccountModel item : listModel) {
                        TradeConsumptionDetail tradeDetail = new TradeConsumptionDetail();//明细表
                        tradeDetail.setId(UUID.randomUUID().toString().substring(0,32));
                        tradeDetail.setMainId(tradeMain.getId());
                        tradeDetail.setFoodId(item.getItemId());
                        tradeDetail.setBusinessTypeId(item.getBusinessTypeId());
                        tradeDetail.setPrice(Double.parseDouble(item.getPrice() + ""));
                        tradeDetail.setQuantity(Double.parseDouble(item.getNumber() + ""));
                        tradeDetail.setActualAmount(tradeDetail.getPrice()*tradeDetail.getQuantity());
                        tradeDetail.setIsXmlOut("0");
                        tradeDetail.setReason("C");
                        tradeDetail.setRefundStatus("0");
                        long count4 = dataBase.insert("trade_consumption_detail", null, parseTradeConsumptionDetail(tradeDetail));

                        Log.e("count4",count4+"");
                        if (count4 != -1)
                            result+=4;
                    }


                }
                dataBase.setTransactionSuccessful();
                dataBase.endTransaction();
            } catch (Exception e) {
            } finally {
                dbManager.closeDatabase(dataBase, null);
            }
            return result;



    }
    /**
     * 将微信交易日志完全转换为ContentValues
     * @param
     * @return
     */
    private ContentValues parseAraStoreLog(AraStoreLog entity) {
        ContentValues cv = new ContentValues();
        cv.put("id", UUID.randomUUID().toString());
        cv.put("amount", entity.getAmount());
        cv.put("orderNo", entity.getOrderNo());
        cv.put("isSyn", entity.getIsSyn());
        cv.put("storeUserId", entity.getStoreUserId());
        cv.put("storeUserName", entity.getStoreUserName());
        cv.put("creatorName", entity.getCreatorName());
        cv.put("creatorId", entity.getCreatorId());
        //String createTime = TimeTools.calendar2String();
        cv.put("createTime",entity.getCreateTime());
        cv.put("isSuccess",entity.getIsSuccess());
        cv.put("zfbAmount",entity.getZfbAmount());
        cv.put("zfType",entity.getZfType());
        //cv.put("synced", CommonValue.STATUS_NO);
        return cv;
    }

    /**
     * 将流水表完全转换为ContentValues
     * @param
     * @return
     */
    private ContentValues parseTradeAccountConsumptionFlow(TradeAccountConsumptionFlow entity) {
        ContentValues cv = new ContentValues();
        cv.put("id", UUID.randomUUID().toString());
        cv.put("restaurant", entity.getRestaurant());
        cv.put("mealTime", entity.getMealTime());
        cv.put("posMachine", entity.getPosMachine());
        cv.put("customer", entity.getCustomer());
        cv.put("accountId", entity.getAccountId());
        cv.put("card", entity.getCard());
        cv.put("operateType", entity.getOperateType());
        cv.put("settlementType", entity.getSettlementType());
        cv.put("flowNo", entity.getFlowNo());
        cv.put("beforeAmount", entity.getBeforeAmount());
        cv.put("actualAmount", entity.getActualAmount());
        cv.put("afterAmount", entity.getAfterAmount());
        cv.put("discountAmount", entity.getDiscountAmount());
        cv.put("beforeTimes", entity.getBeforeTimes());
        cv.put("times", entity.getTimes());
        cv.put("afterTimes", entity.getAfterTimes());
        cv.put("reason", entity.getReason());
        cv.put("isPay", entity.getIsPay());
        cv.put("creatorId", entity.getCreatorId());
        cv.put("creatorName", entity.getCreatorName());
        //String createTime = TimeTools.calendar2String();
        cv.put("createTime",entity.getCreateTime());
        cv.put("isXmlOut",entity.getIsXmlOut());
        cv.put("orderStatus",entity.getOrderStatus());
        //cv.put("synced", CommonValue.STATUS_NO);
        return cv;
    }

    /**
     * 将主表日志完全转换为ContentValues
     * @param
     * @return
     */
    private ContentValues parseTradeConsumptionMain(TradeConsumptionMain entity) {
        ContentValues cv = new ContentValues();
        cv.put("id", entity.getId());
        cv.put("restaurant", entity.getRestaurant());
        cv.put("mealTime", entity.getMealTime());
        cv.put("posMachine", entity.getPosMachine());
        cv.put("flowNo", entity.getFlowNo());
        //String consumptionTime = TimeTools.calendar2String();
        cv.put("consumptionTime",entity.getConsumptionTime());
        cv.put("orderType",entity.getOrderType());
        cv.put("customer", entity.getCustomer());
        cv.put("quantity", entity.getQuantity());
        cv.put("shouldPaidAmount", entity.getShouldPaidAmount());
        cv.put("actualAmount", entity.getActualAmount());
        cv.put("discountPercent", entity.getDiscountPercent());
        cv.put("discountAmount", entity.getDiscountAmount());

        cv.put("reason", entity.getReason());
        cv.put("quotaPrice", entity.getQuotaPrice());
        cv.put("times", entity.getTimes());
        cv.put("isSettlement", entity.getIsSettlement());

        cv.put("creatorId", entity.getCreatorId());
        cv.put("creatorName", entity.getCreatorName());
        //String createTime = TimeTools.calendar2String();
        cv.put("createTime",entity.getCreateTime());
        cv.put("isXmlOut",entity.getIsXmlOut());
        cv.put("customerAddress",entity.getCustomerAddress());
        cv.put("customerPhone",entity.getCustomerPhone());
        cv.put("tableNo",entity.getTableNo());
        cv.put("customerArchitecture",entity.getCustomerArchitecture());
        cv.put("customerName",entity.getCustomerName());
        cv.put("customerFloor",entity.getCustomerFloor());
        cv.put("printStatus",entity.getPrintStatus());
        //cv.put("synced", CommonValue.STATUS_NO);
        cv.put("orderStatus",entity.getOrderStatus());
        return cv;
    }

    /**
     * 将明细表完全转换为ContentValues
     * @param
     * @return
     */
    private ContentValues parseTradeConsumptionDetail(TradeConsumptionDetail entity) {
        ContentValues cv = new ContentValues();
        cv.put("id", UUID.randomUUID().toString());
        cv.put("mainId", entity.getMainId());
        cv.put("foodId", entity.getFoodId());
        cv.put("businessTypeId", entity.getBusinessTypeId());
        cv.put("price", entity.getPrice());
        cv.put("quantity", entity.getQuantity());
        cv.put("actualAmount", entity.getActualAmount());
        cv.put("handDiscount", entity.getHandDiscount());
        cv.put("reason", entity.getReason());
        cv.put("isXmlOut", entity.getIsXmlOut());
        cv.put("refundStatus",entity.getRefundStatus());
        //cv.put("synced", CommonValue.STATUS_NO);
        return cv;
    }

    /**
     * 查询上传微信log(未上传的isSyn为0)
     */
    public  List<AraStoreLog> queryUploadAraStoreLog() {
        Cursor cursor = null;
        RowMapper<AraStoreLog> rowMapper = new RowMapper<AraStoreLog>() {
            @Override
            public AraStoreLog mapRow(Cursor cursor, int index) {
                return TaskManager.this.mapUploadAraStoreLog(cursor, index);
            }
        };
        try {
            if (dataBase == null) {
                dataBase = dbManager.openDatabase();
            }
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DATE,-7);
            String startOfDay = TimeTools.startOfDay(calendar);
            /* String endOfDay = TimeTools.endOfDay(calendar);*/
            StringBuilder str = new StringBuilder("select * from ara_store_log t  ");
            str.append(" where isSyn = '0' ");
           // str.append(" and createTime<= ").append("'"+endOfDay+"'");
            str.append(" and createTime>= ").append("'"+startOfDay+"'");

            cursor = dataBase.rawQuery(str.toString(), null);
            List<AraStoreLog> list = new ArrayList<AraStoreLog>();
            while (cursor.moveToNext()) {
                AraStoreLog araStoreLog = rowMapper.mapRow(cursor, cursor.getPosition());
                list.add(araStoreLog);
            }
            return list;
        } finally {
            dbManager.closeDatabase(dataBase, cursor);
        }

    }
    /**
     * 查询微信log(未上传的isSyn为0)
     */
    public  AraStoreLog queryAraStoreLog(String orderNo) {
        Cursor cursor = null;
        RowMapper<AraStoreLog> rowMapper = new RowMapper<AraStoreLog>() {
            @Override
            public AraStoreLog mapRow(Cursor cursor, int index) {
                return TaskManager.this.mapUploadAraStoreLog(cursor, index);
            }
        };
        try {
            if (dataBase == null) {
                dataBase = dbManager.openDatabase();
            }
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DATE,-7);
            String startOfDay = TimeTools.startOfDay(calendar);
            /* String endOfDay = TimeTools.endOfDay(calendar);*/
            StringBuilder str = new StringBuilder("select * from ara_store_log t  ");
            str.append(" where isSyn = '0' ");
            // str.append(" and createTime<= ").append("'"+endOfDay+"'");
            str.append(" and orderNo= ").append("'"+orderNo+"'");

            cursor = dataBase.rawQuery(str.toString(), null);
            List<AraStoreLog> list = new ArrayList<AraStoreLog>();
            AraStoreLog araStoreLog = new AraStoreLog();
            while (cursor.moveToNext()) {
                 araStoreLog = rowMapper.mapRow(cursor, cursor.getPosition());
            }
            return araStoreLog;
        } finally {
            dbManager.closeDatabase(dataBase, cursor);
        }

    }
    /**将查询的结果AraStoreLog行转换为对象
     * @param cursor
     * @param position
     * @return
     */
    private AraStoreLog mapUploadAraStoreLog(Cursor cursor, int position) {
        AraStoreLog spe = new AraStoreLog();
        spe.setId(cursor.getString(cursor.getColumnIndex("id")));
        spe.setAmount(cursor.getString(cursor.getColumnIndex("amount")));
        spe.setOrderNo(cursor.getString(cursor.getColumnIndex("orderNo")));
        spe.setIsSyn(cursor.getString(cursor.getColumnIndex("isSyn")));
        String createTime = cursor.getString(cursor.getColumnIndex("createTime"));
//        try {
           // Calendar createTime = TimeTools.string2Calendar(getCreateTime);
           // Log.e("时间",TimeTools.calendar2String(createTime));
            spe.setCreateTime(createTime);
//        } catch (ParseException e) {
//            e.printStackTrace();
//        }
        spe.setCreatorId(cursor.getString(cursor.getColumnIndex("creatorId")));
        spe.setCreatorName(cursor.getString(cursor.getColumnIndex("creatorName")));
        spe.setIsSuccess(cursor.getString(cursor.getColumnIndex("isSuccess")));
        spe.setZfbAmount(cursor.getString(cursor.getColumnIndex("zfbAmount")));
        spe.setZfType(cursor.getString(cursor.getColumnIndex("zfType")));
        return spe;
    }

    /**
     * 查询需要上传的flow表信息(未上传的)
     */

    public List<TradeAccountConsumptionFlow> queryUploadConsumptionFlow() {
        Cursor cursor = null;
        RowMapper<TradeAccountConsumptionFlow> rowMapper = new RowMapper<TradeAccountConsumptionFlow>() {
            @Override
            public TradeAccountConsumptionFlow mapRow(Cursor cursor, int index) {
                return TaskManager.this.mapUploadConsumptionFlow(cursor, index);
            }
        };
        List<TradeAccountConsumptionFlow> list = new ArrayList<TradeAccountConsumptionFlow>();
        try {
            if (dataBase == null) {
                dataBase = dbManager.openDatabase();
            }
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DATE,-7);
            String startOfDay = TimeTools.startOfDay(calendar);
            /* String endOfDay = TimeTools.endOfDay(calendar);*/
            StringBuilder str = new StringBuilder("select * from trade_account_consumption_flow t  ");
            str.append(" where isXmlOut = '0' ");
//             str.append(" and createTime<= ").append("'"+endOfDay+"'");
             str.append(" and createTime>= ").append("'"+startOfDay+"'");

            cursor = dataBase.rawQuery(str.toString(), null);

            while (cursor.moveToNext()) {
                TradeAccountConsumptionFlow tradeFlow = rowMapper.mapRow(cursor, cursor.getPosition());
                list.add(tradeFlow);
            }
        } finally {
            dbManager.closeDatabase(dataBase, cursor);
        }
        return list;
    }

    /**
     * 订单flow表信息(页面展示，时间倒叙)
     */
    public List<TradeAccountConsumptionFlow> listTradeFlow() {
        String selection  = " createTime>=? ";
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE,-2);
        String timeStr = TimeTools.calendar2String(calendar);
//        timeStr = "2019-05-14 00:00:00";
        String[] selectionArgs = new String[]{timeStr};

        return listQuery("trade_account_consumption_flow", null, selection, selectionArgs, " createTime desc",
                new RowMapper<TradeAccountConsumptionFlow>() {
                    @Override
                    public TradeAccountConsumptionFlow mapRow(Cursor cursor, int index) {
                        return TaskManager.this.mapUploadConsumptionFlow(cursor, index);
                    }
                });
    }

    /**将查询的结果TradeAccountConsumptionFlow行转换为对象
     * @param cursor
     * @param position
     * @return
     */
    private TradeAccountConsumptionFlow mapUploadConsumptionFlow(Cursor cursor, int position) {
        TradeAccountConsumptionFlow spe = new TradeAccountConsumptionFlow();
        spe.setId(cursor.getString(cursor.getColumnIndex("id")));
        spe.setRestaurant(cursor.getString(cursor.getColumnIndex("restaurant")));
        spe.setMealTime(cursor.getString(cursor.getColumnIndex("mealTime")));
        spe.setPosMachine(cursor.getString(cursor.getColumnIndex("posMachine")));
        spe.setCustomer(cursor.getString(cursor.getColumnIndex("customer")));
        spe.setAccountId(cursor.getString(cursor.getColumnIndex("accountId")));
        spe.setCard(cursor.getString(cursor.getColumnIndex("card")));
        spe.setOperateType(cursor.getString(cursor.getColumnIndex("operateType")));
        spe.setSettlementType(cursor.getString(cursor.getColumnIndex("settlementType")));
        spe.setFlowNo(cursor.getString(cursor.getColumnIndex("flowNo")));
        if (cursor.getString(cursor.getColumnIndex("beforeAmount"))!=null){
            spe.setBeforeAmount(cursor.getDouble(cursor.getColumnIndex("beforeAmount")));
        }
        if (cursor.getString(cursor.getColumnIndex("actualAmount"))!=null){
            spe.setActualAmount(cursor.getDouble(cursor.getColumnIndex("actualAmount")));
        }
        if (cursor.getString(cursor.getColumnIndex("discountAmount"))!=null){
            spe.setDiscountAmount(cursor.getDouble(cursor.getColumnIndex("discountAmount")));
        }
       if (cursor.getString(cursor.getColumnIndex("beforeTimes"))!=null){
           spe.setBeforeTimes(Integer.parseInt(cursor.getString(cursor.getColumnIndex("beforeTimes"))));
       }
         if (cursor.getString(cursor.getColumnIndex("times"))!=null){
             spe.setTimes(Integer.parseInt(cursor.getString(cursor.getColumnIndex("times"))));
       }
         if (cursor.getString(cursor.getColumnIndex("afterTimes"))!=null){
             spe.setAfterTimes(Integer.parseInt(cursor.getString(cursor.getColumnIndex("afterTimes"))));
       }
        spe.setReason(cursor.getString(cursor.getColumnIndex("reason")));
        spe.setIsPay(cursor.getString(cursor.getColumnIndex("isPay")));

        String createTime = cursor.getString(cursor.getColumnIndex("createTime"));
//        try {
//            Calendar createTime = TimeTools.string2Calendar(getCreateTime);
            spe.setCreateTime(createTime);
//        } catch (ParseException e) {
  //          e.printStackTrace();
 //       }
        spe.setCreatorId(cursor.getString(cursor.getColumnIndex("creatorId")));
        spe.setCreatorName(cursor.getString(cursor.getColumnIndex("creatorName")));
        spe.setIsXmlOut(cursor.getString(cursor.getColumnIndex("isXmlOut")));
        spe.setOrderStatus(cursor.getString(cursor.getColumnIndex("orderStatus")));
        return spe;
    }

   /**
     * 查询需要上传的main表信息(未上传的)
     */

    public List<TradeConsumptionMain> queryUploadConsumptionMain(String time) {
        Cursor cursor = null;
        RowMapper<TradeConsumptionMain> rowMapper = new RowMapper<TradeConsumptionMain>() {
            @Override
            public TradeConsumptionMain mapRow(Cursor cursor, int index) {
                return TaskManager.this.mapUploadConsumptionMain(cursor, index);
            }
        };
        try {
            if (dataBase == null) {
                dataBase = dbManager.openDatabase();
            }
           /* Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DATE,-1);
            String startOfDay = TimeTools.startOfDay(calendar);
            String endOfDay = TimeTools.endOfDay(calendar);*/
            StringBuilder str = new StringBuilder("select * from trade_consumption_main t  ");
            str.append(" where isXmlOut = '1' ");
             str.append(" and createTime < ").append("'"+time+"'");
            // str.append(" and createTime>= ").append("'"+startOfDay+"'");

            cursor = dataBase.rawQuery(str.toString(), null);
            List<TradeConsumptionMain> list = new ArrayList<TradeConsumptionMain>();
            while (cursor.moveToNext()) {
                TradeConsumptionMain tradeMain = rowMapper.mapRow(cursor, cursor.getPosition());
                list.add(tradeMain);
            }
            return list;
        } finally {
            dbManager.closeDatabase(dataBase, cursor);
        }

       /* int i = 0;
        String selection  = " isXmlOut = ? ";
        String[] selectionArgs = new String[]{0+""};

        return listQuery("trade_consumption_main", null, null, null, null,
                new RowMapper<TradeConsumptionMain>() {
                    @Override
                    public TradeConsumptionMain mapRow(Cursor cursor, int index) {
                        return TaskManager.this.mapUploadConsumptionMain(cursor, index);
                    }
                });*/
    }
    /**
     * tradeMain表信息(按流水号flowNo)
     */

    public List<TradeConsumptionMain> listTradeMain(String flowNo) {
        String selection  = " flowNo=? and orderStatus=?";
        String[] selectionArgs = new String[]{flowNo,"1"};
        return listQuery("trade_consumption_main", null, selection, selectionArgs,null,
                new RowMapper<TradeConsumptionMain>() {
                    @Override
                    public TradeConsumptionMain mapRow(Cursor cursor, int index) {
                        return TaskManager.this.mapUploadConsumptionMain(cursor, index);
                    }
                });
    }
    /**
     * tradeMain表信息(按流水号flowNo)
     */

    public List<TradeConsumptionMain> listTradeMainByOrderStatus(String flowNo) {
        String selection  = " flowNo=? and orderStatus=?";
        String[] selectionArgs = new String[]{flowNo,"0"};
        return listQuery("trade_consumption_main", null, selection, selectionArgs,null,
                new RowMapper<TradeConsumptionMain>() {
                    @Override
                    public TradeConsumptionMain mapRow(Cursor cursor, int index) {
                        return TaskManager.this.mapUploadConsumptionMain(cursor, index);
                    }
                });
    }

    /**TradeConsumptionMain
     * @param cursor
     * @param position
     * @return
     */
    private TradeConsumptionMain mapUploadConsumptionMain(Cursor cursor, int position) {
        TradeConsumptionMain spe = new TradeConsumptionMain();
        spe.setId(cursor.getString(cursor.getColumnIndex("id")));
        spe.setRestaurant(cursor.getString(cursor.getColumnIndex("restaurant")));
        spe.setMealTime(cursor.getString(cursor.getColumnIndex("mealTime")));
        spe.setPosMachine(cursor.getString(cursor.getColumnIndex("posMachine")));
        spe.setCustomer(cursor.getString(cursor.getColumnIndex("customer")));
        spe.setFlowNo(cursor.getString(cursor.getColumnIndex("flowNo")));
        String consumptionTime = cursor.getString(cursor.getColumnIndex("consumptionTime"));
//        try {
//            Calendar consumptionTime = TimeTools.string2Calendar(getConsumptionTime);
            spe.setConsumptionTime(consumptionTime);
//        } catch (ParseException e) {
//            e.printStackTrace();
//        }
        spe.setOrderType(cursor.getString(cursor.getColumnIndex("orderType")));
        spe.setCustomer(cursor.getString(cursor.getColumnIndex("customer")));
        if (cursor.getString(cursor.getColumnIndex("quantity"))!=null){
            spe.setQuantity(Double.parseDouble(cursor.getString(cursor.getColumnIndex("quantity"))));
        }
        if (cursor.getString(cursor.getColumnIndex("customerAddress"))!=null){
            spe.setCustomerAddress(cursor.getString(cursor.getColumnIndex("customerAddress")));
        }
        if (cursor.getString(cursor.getColumnIndex("customerPhone"))!=null){
            spe.setCustomerPhone(cursor.getString(cursor.getColumnIndex("customerPhone")));
        }
        if (cursor.getString(cursor.getColumnIndex("customerName"))!=null){
            spe.setCustomerName(cursor.getString(cursor.getColumnIndex("customerName")));
        }
        if (cursor.getString(cursor.getColumnIndex("customerFloor"))!=null){
            spe.setCustomerFloor(cursor.getString(cursor.getColumnIndex("customerFloor")));
        }
        if (cursor.getString(cursor.getColumnIndex("customerArchitecture"))!=null){
            spe.setCustomerArchitecture(cursor.getString(cursor.getColumnIndex("customerArchitecture")));
        }
        if (cursor.getString(cursor.getColumnIndex("tableNo"))!=null){
            spe.setTableNo(cursor.getString(cursor.getColumnIndex("tableNo")));
        }
        if (cursor.getString(cursor.getColumnIndex("printStatus"))!=null){
            spe.setPrintStatus(cursor.getString(cursor.getColumnIndex("printStatus")));
        }
        if (cursor.getString(cursor.getColumnIndex("orderStatus"))!=null){
            spe.setOrderStatus(cursor.getString(cursor.getColumnIndex("orderStatus")));
        }
       if (cursor.getString(cursor.getColumnIndex("shouldPaidAmount"))!=null){
            spe.setShouldPaidAmount(Double.parseDouble(cursor.getString(cursor.getColumnIndex("shouldPaidAmount"))));
        }
        if (cursor.getString(cursor.getColumnIndex("actualAmount"))!=null){
            spe.setActualAmount(Double.parseDouble(cursor.getString(cursor.getColumnIndex("actualAmount"))));
        }
        if (cursor.getString(cursor.getColumnIndex("discountPercent"))!=null){
            spe.setDiscountPercent(Double.parseDouble(cursor.getString(cursor.getColumnIndex("discountPercent"))));
        }
         if (cursor.getString(cursor.getColumnIndex("discountAmount"))!=null){
             spe.setDiscountAmount(Double.parseDouble(cursor.getString(cursor.getColumnIndex("discountAmount"))));
         }
         if (cursor.getString(cursor.getColumnIndex("quotaPrice"))!=null){
             spe.setQuotaPrice(Double.parseDouble(cursor.getString(cursor.getColumnIndex("quotaPrice"))));
         }
        if (cursor.getString(cursor.getColumnIndex("times"))!=null){
            spe.setTimes(Integer.parseInt(cursor.getString(cursor.getColumnIndex("times"))));
         }
        spe.setReason(cursor.getString(cursor.getColumnIndex("reason")));
        spe.setIsSettlement(cursor.getString(cursor.getColumnIndex("isSettlement")));

        String createTime = cursor.getString(cursor.getColumnIndex("createTime"));
//        try {
//            Calendar createTime = TimeTools.string2Calendar(getCreateTime);
            spe.setCreateTime(createTime);
//        } catch (ParseException e) {
//            e.printStackTrace();
//        }
        spe.setCreatorId(cursor.getString(cursor.getColumnIndex("creatorId")));
        spe.setCreatorName(cursor.getString(cursor.getColumnIndex("creatorName")));
        spe.setIsXmlOut(cursor.getString(cursor.getColumnIndex("isXmlOut")));
        return spe;
    }


    /**
     * 查询需要上传的detail表信息(未上传的)
     */

    public List<TradeConsumptionDetail> queryUploadConsumptionDetail() {
        Cursor cursor = null;
        RowMapper<TradeConsumptionDetail> rowMapper = new RowMapper<TradeConsumptionDetail>() {
            @Override
            public TradeConsumptionDetail mapRow(Cursor cursor, int index) {
                return TaskManager.this.mapUploadConsumptionDetail(cursor, index);
            }
        };
        try {
            if (dataBase == null) {
                dataBase = dbManager.openDatabase();
            }
           /* Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DATE,-1);
            String startOfDay = TimeTools.startOfDay(calendar);
            String endOfDay = TimeTools.endOfDay(calendar);*/
            StringBuilder str = new StringBuilder("select * from trade_consumption_detail t  ");
            str.append(" where isXmlOut = '0' ");
            // str.append(" and createTime<= ").append("'"+endOfDay+"'");
            // str.append(" and createTime>= ").append("'"+startOfDay+"'");

            cursor = dataBase.rawQuery(str.toString(), null);
            List<TradeConsumptionDetail> list = new ArrayList<TradeConsumptionDetail>();
            while (cursor.moveToNext()) {
                TradeConsumptionDetail tradeDetail = rowMapper.mapRow(cursor, cursor.getPosition());
                list.add(tradeDetail);
            }
            return list;
        } finally {
            dbManager.closeDatabase(dataBase, cursor);
        }

       /* int i = 0;
        String selection  = " isXmlOut = ? ";
        String[] selectionArgs = new String[]{0+""};

        return listQuery("trade_consumption_detail", null, null, null, null,
                new RowMapper<TradeConsumptionDetail>() {
                    @Override
                    public TradeConsumptionDetail mapRow(Cursor cursor, int index) {
                        return TaskManager.this.mapUploadConsumptionDetail(cursor, index);
                    }
                });*/
    }

  /**
     * 查询detail表信息(根据主表mainId)
     */

    public List<TradeConsumptionDetail> listTradeDetail(String mainId) {
        String selection  = " mainId = ? ";
        String[] selectionArgs = new String[]{mainId};
        return listQuery("trade_consumption_detail", null, selection, selectionArgs, null,
                new RowMapper<TradeConsumptionDetail>() {
                    @Override
                    public TradeConsumptionDetail mapRow(Cursor cursor, int index) {
                        return TaskManager.this.mapUploadConsumptionDetail(cursor, index);
                    }
                });
    }
    /**TradeConsumptionDetail
     * @param cursor
     * @param position
     * @return
     */
    private TradeConsumptionDetail mapUploadConsumptionDetail(Cursor cursor, int position) {
        TradeConsumptionDetail spe = new TradeConsumptionDetail();
        spe.setId(cursor.getString(cursor.getColumnIndex("id")));
        spe.setMainId(cursor.getString(cursor.getColumnIndex("mainId")));
        spe.setFoodId(cursor.getString(cursor.getColumnIndex("foodId")));
        spe.setBusinessTypeId(cursor.getString(cursor.getColumnIndex("businessTypeId")));
        if (cursor.getString(cursor.getColumnIndex("price"))!=null){
            spe.setPrice(Double.parseDouble(cursor.getString(cursor.getColumnIndex("price"))));
        }
        if (cursor.getString(cursor.getColumnIndex("quantity"))!=null){
            spe.setQuantity(Double.parseDouble(cursor.getString(cursor.getColumnIndex("quantity"))));
        }
        if (cursor.getString(cursor.getColumnIndex("actualAmount"))!=null){
            spe.setActualAmount(Double.parseDouble(cursor.getString(cursor.getColumnIndex("actualAmount"))));
        }

        spe.setReason(cursor.getString(cursor.getColumnIndex("reason")));
        if (cursor.getString(cursor.getColumnIndex("handDiscount"))!=null){
            spe.setHandDiscount(Double.parseDouble(cursor.getString(cursor.getColumnIndex("handDiscount"))));
        }
        spe.setRefundStatus(cursor.getString(cursor.getColumnIndex("refundStatus")));
        spe.setIsXmlOut(cursor.getString(cursor.getColumnIndex("isXmlOut")));
        return spe;
    }


    /**
     * 删除一个月前的数据
     */
    public void deleteOldData(){
        try {
            if (dataBase == null) {
                dataBase = dbManager.openDatabase();
            }

            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DATE, -7);
            String timeStr = TimeTools.calendar2String(calendar);
            Log.e("DB", "deleteOldData: " + timeStr);

            StringBuffer selection = new StringBuffer(" createTime<? and isSyn = ?");
            String[] selectionArgs = new String[]{timeStr, "1"};
            dataBase.delete("ara_store_log", selection.toString(), selectionArgs);

            selection = new StringBuffer(" createTime < ? and isXmlOut = ?");
            dataBase.delete("trade_account_consumption_flow", selection.toString(), selectionArgs);

            List<TradeConsumptionMain> mains = queryUploadConsumptionMain(timeStr);
            dataBase.delete("trade_consumption_main", selection.toString(), selectionArgs);

            StringBuffer userSelection = new StringBuffer(" lastUseTime<? ");
            String[] userSelectionArgs = new String[]{timeStr};
            dataBase.delete("user_information", userSelection.toString(), userSelectionArgs);
            selection = new StringBuffer("isXmlOut = ? and mainId = ?");
            for (TradeConsumptionMain item : mains) {
                selectionArgs = new String[]{"1", item.getId()};
                dataBase.delete("trade_consumption_detail", selection.toString(), selectionArgs);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            dbManager.closeDatabase(dataBase, null);
        }
    }
    /**
     * 删除支付失败的数据
     */
    public void deleteFailedOrder(String flowNo){
        Cursor cursor = null;
        List<String> list = new  ArrayList();
        try {
            if (dataBase == null) {
                dataBase = dbManager.openDatabase();
            }

            StringBuffer selection = new StringBuffer(" flowNo = ?");
            String[] selectionArgs = new String[]{flowNo};
            dataBase.delete("trade_account_consumption_flow", selection.toString(), selectionArgs);
            dataBase.delete("trade_consumption_main", selection.toString(), selectionArgs);

            cursor = dataBase.query("trade_consumption_main", new String[]{"id"}, "flowNo=?", new String[]{flowNo }, null, null, null, null);
            while (cursor.moveToNext()) {
                list.add(0,cursor.getString(cursor.getColumnIndex("id")));
            }
            if (list != null && list.size() > 0) {
                for (String mainId : list) {
                    dataBase.delete("trade_consumption_detail", "mainId=?", new String[]{mainId});
                }
            }
            Log.e(TAG, "updateStatusFlow: 删除成功【" +  flowNo+"】");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            dbManager.closeDatabase(dataBase, cursor);
        }
    }
    //更新flow三个表数据上传
    public void updateStatusFlow(List<TradeAccountConsumptionFlow> uploadConsumptionFlow, List<String> okFlowLists) {

        boolean flag = okFlowLists != null && okFlowLists.size() > 0;
        if (!flag) return;
        //更新状态
        Cursor cursor = null;
        List<String> list = new  ArrayList();
        ContentValues values = new ContentValues();
        values.put("isXmlOut","1");//key为字段名，value为值
        try {
            if (dataBase == null) {
                dataBase = dbManager.openDatabase();
            }
            dataBase.beginTransaction();
            for (String flowNo : okFlowLists) {
                Log.e(TAG, "updateStatusFlow: 更新状态【" +  flowNo+"】");
                try {
                    dataBase.update("trade_account_consumption_flow", values, "flowNo=?", new String[]{flowNo });
                    dataBase.update("trade_consumption_main", values, "flowNo=?", new String[]{flowNo});
                    cursor = dataBase.query("trade_consumption_main", new String[]{"id"}, "flowNo=?", new String[]{flowNo }, null, null, null, null);
                    while (cursor.moveToNext()) {
                        list.add(0,cursor.getString(cursor.getColumnIndex("id")));
                    }
                    if (list != null && list.size() > 0) {
                        for (String mainId : list) {
                            dataBase.update("trade_consumption_detail", values, "mainId=?", new String[]{mainId});
                        }
                    }
                    Log.e(TAG, "updateStatusFlow: 更新状态成功【" +  flowNo+"】");
                } catch (Exception e) {
                    Log.e(TAG, "updateStatusFlow: 更新状态失败【" +  flowNo+"】");
                }
            }
            dataBase.setTransactionSuccessful();
        } catch (Exception e) {
            Log.e(TAG, "updateStatusFlow: 数据库打开失败");
        } finally {
            dataBase.endTransaction();
            dbManager.closeDatabase(dataBase, cursor);
        }
    }
    //更新flow三个表
    public void updateStatusMain(String flowNo,String logId,String beforeAmount,String afterAmount) {
        //更新状态
        Cursor cursor = null;
        ContentValues values = new ContentValues();
        values.put("orderStatus","1");//key为字段名，value为值
        values.put("printStatus","0");//key为字段名，value为值
        ContentValues value = new ContentValues();
        value.put("isSuccess","1");//key为字段名，value为值
        ContentValues flowValue = new ContentValues();
        flowValue.put("beforeAmount",beforeAmount);//key为字段名，value为值
        flowValue.put("afterAmount",afterAmount);//key为字段名，value为值
        flowValue.put("orderStatus","1");//key为字段名，value为值
        try {
            if (dataBase == null) {
                dataBase = dbManager.openDatabase();
            }
            dataBase.beginTransaction();

            Log.e(TAG, "updateStatusFlow: 更新状态【" +  flowNo+"】");
            try {
                dataBase.update("ara_store_log", value, "id=?", new String[]{logId});
                dataBase.update("trade_account_consumption_flow", flowValue, "flowNo=?", new String[]{flowNo});
                dataBase.update("trade_consumption_main", values, "flowNo=?", new String[]{flowNo});
                Log.e(TAG, "updateStatusFlow: 更新状态成功【" +  flowNo+"】");
            } catch (Exception e) {
                Log.e(TAG, "updateStatusFlow: 更新状态失败【" +  flowNo+"】");
            }
            dataBase.setTransactionSuccessful();
        } catch (Exception e) {
            Log.e(TAG, "updateStatusFlow: 数据库打开失败");
        } finally {
            dataBase.endTransaction();
            dbManager.closeDatabase(dataBase, cursor);
        }
    }
    //删除flow三个表
    public void deleteStatusMain(String flowNo,String logId,String beforeAmount,String afterAmount) {
        //更新状态
        Cursor cursor = null;
        ContentValues values = new ContentValues();
        values.put("orderStatus","1");//key为字段名，value为值
        values.put("printStatus","0");//key为字段名，value为值
        ContentValues value = new ContentValues();
        value.put("isSuccess","1");//key为字段名，value为值
        ContentValues flowValue = new ContentValues();
        flowValue.put("beforeAmount",beforeAmount);//key为字段名，value为值
        flowValue.put("afterAmount",afterAmount);//key为字段名，value为值
        flowValue.put("orderStatus","1");//key为字段名，value为值
        try {
            if (dataBase == null) {
                dataBase = dbManager.openDatabase();
            }
            dataBase.beginTransaction();

            Log.e(TAG, "updateStatusFlow: 更新状态【" +  flowNo+"】");
            try {
                dataBase.update("ara_store_log", value, "id=?", new String[]{logId});
                dataBase.update("trade_account_consumption_flow", flowValue, "flowNo=?", new String[]{flowNo});
                dataBase.update("trade_consumption_main", values, "flowNo=?", new String[]{flowNo});
                Log.e(TAG, "updateStatusFlow: 更新状态成功【" +  flowNo+"】");
            } catch (Exception e) {
                Log.e(TAG, "updateStatusFlow: 更新状态失败【" +  flowNo+"】");
            }
            dataBase.setTransactionSuccessful();
        } catch (Exception e) {
            Log.e(TAG, "updateStatusFlow: 数据库打开失败");
        } finally {
            dataBase.endTransaction();
            dbManager.closeDatabase(dataBase, cursor);
        }
    }



}
